<?php
/**
 * Created by PhpStorm.
 * User: ewen
 * Date: 4/26/21
 * Time: 3:15 PM
 */

namespace app\common\model;


use app\common\validate\System;
use think\Db;

class AssetFlow extends Common
{

    /**
     * 新增变化记录
     * @param $user_id
     * @param $currency_id
     * @param $amount
     * @param $available
     * @param $flow_type
     * @return AssetFlow
     */
    public static function addFlowLog($user_id, $currency_id, $amount, $available, $flow_type)
    {
        $res = self::add([
            'user_id' => $user_id,
            'uuid' => microsecond() . rand(1, 1000000),
            'currency_id' => $currency_id,
            'amount' => $amount,
            'available' => $available,
            'flow_type' => $flow_type,
            'flow_time' => microsecond()
        ]);
        return $res;
    }

    /**
     * 获取TXUSD记录表
     * @param $userID
     * @param int $per
     * @return \think\Paginator
     */
    public static function getTxUsdLog($userID, $per = self::DEFAULT_PER_PAGE, $nowLang = 'zh-cn')
    {
        $where = [
            'user_id' => $userID,
            'currency_id' => 1000002
        ];

        $list = self::alias('a')
            ->field('
            a.id,user_id,currency_id,amount,available,a.flow_type,create_time,b.flow_desc
            ')
            ->join('asset_flow_type b', 'a.flow_type = b.flow_type', 'left')
            ->where($where)
            ->order('a.id desc')
            ->paginate($per, false, ['query' => request()->param()])
            ->each(function ($item, $key) use (&$nowLang) {
                if ($nowLang !== 'zh-cn') {
                    switch ($item['flow_type']) {
                        case 100:
                            $item['flow_desc'] = 'sign award';
                            break;
                        case 101:
                            $item['flow_desc'] = 'join partner';
                            break;
                        case 102:
                            $item['flow_desc'] = 'options trade';
                            break;
                        case 103:
                            $item['flow_desc'] = 'contract trade';
                            break;
                        case 104:
                            $item['flow_desc'] = 'fund trade';
                            break;
                        case 105:
                            $item['flow_desc'] = 'continuous trading';
                            break;
                        case 106:
                            $item['flow_desc'] = 'invite';
                            break;
                    }
                }
                return $item;
            });;
        return $list;
    }

    /**
     * 流水查询
     * @param $currency_id
     * @param $flow_type
     * @return float|int
     */
    public static function getSumData($currency_id, $flow_type, $userID)
    {
        $tableExtArr = [
            '202005', '202006', '202007', '202008', '202009', '202010', '202011', '202012',
            '202101', '202102', '202103', '202104', '202105', '202106', '202107', '202108', '202109', '202110', '202111', '202112'
        ];

        $sqlPlus = '(select amount from asset_flow where currency_id = ' . $currency_id . ' and flow_type = ' . $flow_type . ' and amount > 0 and user_id = ' . $userID . ' )';//所有正数
        foreach ($tableExtArr as $k => $v) {
            $sqlPlus .= ' union (select amount from asset_flow_' . $v . ' where currency_id = ' . $currency_id . ' and flow_type = ' . $flow_type . ' and amount > 0 and user_id = ' . $userID . ' )';
        }
        $plusData = Db::query($sqlPlus);
        $plusSum = array_sum(array_column($plusData, 'amount'));


        $sqlMinus = '(select amount from asset_flow where currency_id = ' . $currency_id . ' and flow_type = ' . $flow_type . ' and amount < 0 and user_id = ' . $userID . ' )';//所有负数
        foreach ($tableExtArr as $k => $v) {
            $sqlMinus .= ' union (select amount from asset_flow_' . $v . ' where currency_id = ' . $currency_id . ' and flow_type = ' . $flow_type . ' and amount < 0 and user_id = ' . $userID . ' )';
        }
        $minusData = Db::query($sqlMinus);
        $minusSum = abs(array_sum(array_column($minusData, 'amount')));

        return $minusSum + $plusSum;
    }

    /**
     * 流水查询（指定类型）
     * @param $currency_id
     * @param $flow_type
     * @return float|int
     */
    public static function getSumFlowTypeIncomeData($currency_id, $flow_type, $userID)
    {
        $tableExtArr = [
            '202005', '202006', '202007', '202008', '202009', '202010', '202011', '202012',
            '202101', '202102', '202103', '202104', '202105', '202106', '202107', '202108', '202109', '202110', '202111', '202112'
        ];

        $sqlPlus = '(select amount from asset_flow where currency_id = ' . $currency_id . ' and flow_type in (' . $flow_type . ') and amount > 0 and user_id = ' . $userID . ' )';//所有正数
        foreach ($tableExtArr as $k => $v) {
            $sqlPlus .= ' union (select amount from asset_flow_' . $v . ' where currency_id = ' . $currency_id . ' and flow_type in (' . $flow_type . ') and amount > 0 and user_id = ' . $userID . ' )';
        }
        $plusData = Db::query($sqlPlus);
        $plusSum = array_sum(array_column($plusData, 'amount'));

        return $plusSum;
    }

    /**
     * 获取TXUSD指定类型获取总量
     * @param $userID
     * @param int $currency_id
     * @param string $flow_type
     * @return bool
     */
    public static function getFlowTypeSumIncome($userID, $currency_id = 1000002, $flow_type = '100,101,102,103,104,105,106')
    {
        if (cache(Common::CACHE_SYSTEM_BASE_INFO)) {
            $systemSetting = cache(Common::CACHE_SYSTEM_BASE_INFO);
        } else {
            $systemSetting = XkSystemSetting::get(1);
            cache('systemSetting', $systemSetting);
        }
        $normalMax = $systemSetting['adminLogo'];//普通用户最高奖励
        $airdropMax = $systemSetting['webLogo'];//空投用户最高奖励
        $userInfo = WebUser::get($userID);
        !$userInfo && backError(lang('invalid user id'));
        if($userInfo['userType']==1){
            //  普通用户
            $assignAmount = $normalMax;
        }else{
            //  空投用户
            $assignAmount = $airdropMax;
        }
        //  总奖励流水
        $sum = self::getSumFlowTypeIncomeData($currency_id, $flow_type, $userID);
        $rate = self::TXUSD_USD_RATE;
//        $sum/$assignAmount = $rate;
        $amount = $sum / $rate;
        $amount > $assignAmount && backError(lang('maximum award') . $assignAmount . 'U');
        return true;
    }

    /**
     * 获取连续交易天数
     */
    public static function getDaysLog($userID, $flow_type = '9002,8001', $days = 7)
    {
        //  获取指定日期
        $dateArr = [
            [
                'date' => date('Y-m-d'),
                'startTime' => date('Y-m-d 00:00:00'),
                'endTime' => date('Y-m-d 23:59:59')
            ]
        ];

        for ($x = 1; $x < $days; $x++) {
            $day = date('Y-m-d', strtotime("-" . $x . " days", strtotime(date('Y-m-d'))));
            $dateArr[] = [
                'date' => $day,
                'startTime' => date('Y-m-d 00:00:00', strtotime($day)),
                'endTime' => date('Y-m-d 23:59:59', strtotime($day))
            ];
        }

        $tableExtArr = [
            '202005', '202006', '202007', '202008', '202009', '202010', '202011', '202012',
            '202101', '202102', '202103', '202104', '202105', '202106', '202107', '202108', '202109', '202110', '202111', '202112'
        ];

        $conNum = 0;
        foreach ($dateArr as $kk => $vv) {
            //  查询每天是否有数据
            $sql = '(select id from asset_flow where flow_type in (' . $flow_type . ') and user_id = ' . $userID . ' and create_time >= "' . $vv['startTime'] . '" and create_time <= "' . $vv['endTime'] . '" )';//所有正数
            foreach ($tableExtArr as $k => $v) {
                $sql .= ' union (select id from asset_flow where flow_type in (' . $flow_type . ') and user_id = ' . $userID . ' and create_time >= "' . $vv['startTime'] . '" and create_time <= "' . $vv['endTime'] . '" )';
            }
            $res = Db::query($sql);
            if (count($res)) {
                $conNum++;
            } else {
                if ($vv['date'] !== date('Y-m-d')) return $conNum;
            }
        }
        return $conNum;
    }

}